package com.shanghaionstar.user;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.DatePicker;
import android.widget.LinearLayout;

import com.onstar.cn.auth.userProfile.Vehicle;
import com.onstar.cn.common.exception.OnStarException;
import com.onstar.cn.common.util.CommonUtil;
import com.onstar.cn.common.util.PreferencesUtls;
import com.onstar.cn.framework.annotation.FindViewById;
import com.onstar.cn.framework.common.CustomLayoutsGroup;
import com.onstar.cn.framework.mvp.base.core.BaseActivity;
import com.onstar.cn.framework.mvp.base.core.BaseFragment;
import com.onstar.cn.mag.PlateEngineNumEntity;
import com.onstar.cn.weight.ProgressLayout;
import com.onstar.cn.weight.discover.ItemViewData;
import com.shanghaionstar.R;
import com.shanghaionstar.activity.MoreActivity;
import com.shanghaionstar.enumtype.FunctionNameFindId;
import com.shanghaionstar.home.life.AlarmManagerUtil;
import com.shanghaionstar.user.iview.IVehicleInfoView;
import com.shanghaionstar.user.presenter.VehicleInfoPresenter;
import com.shanghaionstar.utils.AlertDialogUtil;
import com.shanghaionstar.utils.ApplicationUtil;
import com.shanghaionstar.utils.FinalConstants;
import com.shanghaionstar.utils.JoinMeConstants;
import com.shanghaionstar.vehicle_ownerlife.VehicleInspectionManager;
import com.shanghaionstar.weight.TopLayout;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;

/**
 * Created by 7828wc on 16/6/29.
 */
public class VehicleInfoFragment extends BaseFragment implements IVehicleInfoView {
    @FindViewById
    private LinearLayout datas_layout;
    @FindViewById
    private LinearLayout thirds_layout;
    @FindViewById
    private TopLayout top_layout;
    @FindViewById
    private ProgressLayout progress_layout;
    private VehicleInfoPresenter presenter;
    private MoreActivity parentActivity;
    private String compulsoryInsuranceExpireDate, businessInsuranceExpireDate;
    private String plateNumber = "";
    private String engineNumber = "";
    private String insuranceComp = "";

    @Override
    public int getLayoutId() {
        return R.layout.more_vehicle_info;

    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        parentActivity = (MoreActivity) activity;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        btnBackClick(top_layout);
        if (isFirstLoad()) {
            presenter = new VehicleInfoPresenter(parentActivity.getScheduler());
            presenter.setView(this);
        }
        this.presenter.updateVehicleInfo("", "", "", true);
        this.presenter.start();
    }

    @Override
    public void onResume() {
        super.onResume();
     /*       String engineNumber = parentActivity.getEngineNumber();
            String plateNumber = parentActivity.getPlateNumber();
            String insuranceComp = parentActivity.getInsuranceComp();*/
        String engineNumber = PreferencesUtls.getInstance(parentActivity).getString("engineNumber", "");
        String plateNumber = PreferencesUtls.getInstance(parentActivity).getString("plateNumber", "");
        String insuranceComp = PreferencesUtls.getInstance(parentActivity).getString("insuranceComp", "");
        if (TextUtils.isEmpty(engineNumber)) {
            engineNumber = parentActivity.getEngineNumber();
        }
        if (TextUtils.isEmpty(plateNumber)) {
            plateNumber = parentActivity.getPlateNumber();
        }
        if (TextUtils.isEmpty(insuranceComp)) {
            insuranceComp = parentActivity.getInsuranceComp();
        }
/*        String engineNumber = parentActivity.getEngineNumber();
            String plateNumber = parentActivity.getPlateNumber();*/
        String businessInsuranceExpireDate = parentActivity.getBusinessInsuranceExpireDate();
        String compulsoryInsuranceExpireDate = parentActivity.getCompulsoryInsuranceExpireDate();
        showDatas(plateNumber, engineNumber, businessInsuranceExpireDate, compulsoryInsuranceExpireDate, insuranceComp);
        PreferencesUtls.getInstance(parentActivity).putString("engineNumber", "");
        PreferencesUtls.getInstance(parentActivity).putString("plateNumber", "");
        PreferencesUtls.getInstance(parentActivity).putString("insuranceComp", "");

        new VehicleInspectionManager((BaseActivity) onActivity()).getDrivingLicenseDate();

    }

    private void showDatas(String plateNumber, String engineNumber, String businessInsuranceExpireDate, String compulsoryInsuranceExpireDate, String insuranceComp) {
        datas_layout.removeAllViews();
        thirds_layout.removeAllViews();

        List<ItemViewData> datas = new ArrayList<ItemViewData>();
        ItemViewData viewData = null;
        Vehicle vehicleInfo = ApplicationUtil.getInstance().getCurrentVehicle();

        viewData = new ItemViewData();
        viewData.setText(getString(R.string.option_vin));
        String vin = vehicleInfo == null ? null : vehicleInfo.getVin();
        viewData.setRightText(vin == null ? "" : CommonUtil.maskWithStar(vin, 3, 4));
        viewData.setShowRightArrow(false);
        datas.add(viewData);

        viewData = new ItemViewData();
        viewData.setText(getString(R.string.more_vehicle_make_model));
        viewData.setRightText(vehicleInfo == null || vehicleInfo.getModelDesc() == null ? "" : vehicleInfo.getModelDesc());
        viewData.setShowRightArrow(false);
        datas.add(viewData);

        viewData = new ItemViewData();
        viewData.setText(getString(R.string.more_vehicle_year));
        viewData.setRightText(vehicleInfo == null ? "" : vehicleInfo.getYear());
        viewData.setShowRightArrow(false);
        datas.add(viewData);

        viewData = new ItemViewData();
        viewData.setText(getString(R.string.change_vehicle));
        viewData.setFunctionValue(FunctionNameFindId.Vehicle_SwitchVehicles.getStringValue());
        String model = vehicleInfo == null ? "" : vehicleInfo.getMakeDesc() + vehicleInfo.getModelDesc();
        viewData.setRightText(model);
        //  viewData.setShowRightArrow(false);
//        if (ApplicationUtil.getInstance().getLoginRole().equalsIgnoreCase(JoinMeConstants.OWNER)) {
//            viewData.setClassName(MoreActivity.class.getName());
//            Bundle chooseVehicleImgBundle = new Bundle();
//            chooseVehicleImgBundle.putString(FinalConstants.JUMP_FLAG, ChooseVehicleImgFragment.class.getName());
//            viewData.setBundle(chooseVehicleImgBundle);
//            viewData.setShowRightArrow(true);
//        } else {
//            viewData.setShowRightArrow(false);
//        }
        if (ApplicationUtil.getInstance().isChangingVehicleAllowed()) {
            viewData.setClassName(MoreActivity.class.getName());
            Bundle selectVehicleBundle = new Bundle();
            selectVehicleBundle.putString(FinalConstants.JUMP_FLAG, ChangeVehicleFragment.class.getName());
            viewData.setBundle(selectVehicleBundle);
            viewData.setShowRightArrow(true);
        } else {
            viewData.setShowRightArrow(false);
            viewData.setText(getString(R.string.shift_car));
        }
        datas.add(viewData);

        viewData = new ItemViewData();
        viewData.setText(getString(R.string.option_plate_number));
        viewData.setFunctionValue(FunctionNameFindId.Vehicle_Plate.getStringValue());
        viewData.setRightText(plateNumber);
        if (ApplicationUtil.getInstance().getLoginRole().equalsIgnoreCase(JoinMeConstants.OWNER)) {
            viewData.setClassName(MoreActivity.class.getName());
            Bundle emailBundle = new Bundle();
            emailBundle.putString(FinalConstants.JUMP_FLAG, SetPlateNumberFragment.class.getName());
            emailBundle.putString(FinalConstants.PlateEngineNumber.PLATE_ENGINE_FLAG, PlateAndEngineEnum.PlateNumber.name());
            emailBundle.putString(PlateAndEngineEnum.PlateNumber.name(), plateNumber);
            viewData.setBundle(emailBundle);
            viewData.setShowRightArrow(true);
        } else {
            viewData.setShowRightArrow(false);
        }
        datas.add(viewData);

      /* viewData = new ItemViewData();
        viewData.setText(getString(R.string.vehicle_info));
        viewData.setClassName(MoreActivity.class.getName());
        Bundle vehicBundle = new Bundle();
        vehicBundle.putString(FinalConstants.JUMP_FLAG, VehicleInfoFragment.class.getName());
        viewData.setBundle(vehicBundle);
        datas.add(viewData);
*/
        viewData = new ItemViewData();
        viewData.setText(getString(R.string.option_engine));
        viewData.setFunctionValue(FunctionNameFindId.Vehicle_Engine.getStringValue());
        viewData.setRightText(engineNumber);
        if (ApplicationUtil.getInstance().getLoginRole().equalsIgnoreCase(JoinMeConstants.OWNER)) {
            viewData.setClassName(MoreActivity.class.getName());
            Bundle engineBundle = new Bundle();
            engineBundle.putString(FinalConstants.JUMP_FLAG, SetPlateNumberFragment.class.getName());
            engineBundle.putString(FinalConstants.PlateEngineNumber.PLATE_ENGINE_FLAG, PlateAndEngineEnum.EngineNumber.name());
            engineBundle.putString(PlateAndEngineEnum.EngineNumber.name(), engineNumber);
            viewData.setBundle(engineBundle);
            viewData.setShowRightArrow(true);
        } else {
            viewData.setShowRightArrow(false);
        }
        datas.add(viewData);


        CustomLayoutsGroup group = new CustomLayoutsGroup(getActivity(), datas);
        group.customLineLayoutGroup(datas_layout);

        group.setOnViewItemClickListener(new CustomLayoutsGroup.OnViewItemClickListener() {
            @Override
            public boolean onViewItemClick(ItemViewData item) {
                return true;
            }
        });

        if (JoinMeConstants.OWNER.equalsIgnoreCase(ApplicationUtil.getInstance().getLoginRole())) {
            List<ItemViewData> thirdsDatas = new ArrayList<ItemViewData>();
            ItemViewData thirdsViewData = new ItemViewData();
            thirdsViewData.setText(getString(R.string.more_vehicle_insurance_company));
            thirdsViewData.setRightText(insuranceComp);
            thirdsViewData.setFunctionValue(FunctionNameFindId.Vehicle_InsuranceCo.getStringValue());
            thirdsViewData.setClassName(MoreActivity.class.getName());
            Bundle emailBundle = new Bundle();
            emailBundle.putString(FinalConstants.JUMP_FLAG, UpdateInsuranceCompanyFragment.class.getName());
            emailBundle.putString(FinalConstants.PAGE_JUMP, insuranceComp);
            thirdsViewData.setBundle(emailBundle);
            thirdsDatas.add(thirdsViewData);


            thirdsViewData = new ItemViewData();
            thirdsViewData.setText(getString(R.string.more_vehicle_insurance_due_date));
            thirdsViewData.setRightText(compulsoryInsuranceExpireDate);
            thirdsViewData.setFunctionValue(FunctionNameFindId.Vehicle_ComplusInsurExpiry.getStringValue());
            thirdsDatas.add(thirdsViewData);

            thirdsViewData = new ItemViewData();
            thirdsViewData.setText(getString(R.string.more_vehicle_business_insurance_due_date));
            thirdsViewData.setRightText(businessInsuranceExpireDate);
            thirdsViewData.setFunctionValue(FunctionNameFindId.Vehicle_CommercInsurExpiry.getStringValue());
            thirdsDatas.add(thirdsViewData);


            CustomLayoutsGroup thidsGroup = new CustomLayoutsGroup(getActivity(), thirdsDatas);
            thidsGroup.customLineLayoutGroup(thirds_layout);

            thidsGroup.setOnViewItemClickListener(new CustomLayoutsGroup.OnViewItemClickListener() {
                @Override
                public boolean onViewItemClick(ItemViewData item) {
                    if (item.getText().equalsIgnoreCase(getString(R.string.more_vehicle_insurance_due_date))) {
                        showDatePicker(item.getRightText(), false);
                        return false;
                    }
                    if (item.getText().equalsIgnoreCase(getString(R.string.more_vehicle_business_insurance_due_date))) {
                        showDatePicker(item.getRightText(), true);
                        return false;
                    }
                    return true;
                }
            });
        }
    }


    private void showDatePicker(String dateString, final boolean isBusiness) {
        SimpleDateFormat sdf = new SimpleDateFormat(FinalConstants.DATE_FORMAT);
        Calendar calendar = Calendar.getInstance(Locale.CHINA);
        try {
            Date date = sdf.parse(dateString);
            calendar.setTime(date);
        } catch (Exception e) {
            e.printStackTrace();
            calendar.setTime(new Date(System.currentTimeMillis()));
        }
//        DatePickerDialog datePickerDialog = new DatePickerDialog(getActivity(), R.style.timePickerDialog,new DatePickerDialog.OnDateSetListener() {
        DatePickerDialog datePickerDialog = new DatePickerDialog(getActivity(), new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker datePicker, int year, int montyOfYear, int dayOfMonth) {
                StringBuilder sb = new StringBuilder();
                sb.append(year);
                sb.append("-");
                sb.append((montyOfYear + 1) < 10 ? 0 + (montyOfYear + 1) : (montyOfYear + 1));
                sb.append("-");
                sb.append(dayOfMonth);
                if (!isBusiness) {
                    compulsoryInsuranceExpireDate = sb.toString();
                } else {
                    businessInsuranceExpireDate = sb.toString();
                }
                AlarmManagerUtil.notifyAssuranceExpireDate(getActivity(), sb, isBusiness);
                presenter.updateVehicleInfo("", isBusiness ? "" : sb.toString(), isBusiness ? sb.toString() : "", false);
                presenter.start();
            }
        }, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH));
        datePickerDialog.show();
    }


    @Override
    public void setLoading(boolean isLoading) {
        progress_layout.setVisibility(isLoading ? View.VISIBLE : View.GONE);
    }

    @Override
    public void onResponseError(OnStarException e) {
        AlertDialogUtil.showDialogByOnstarException(onActivity(), e);
    }

    @Override
    public void onReponseSuccess(PlateEngineNumEntity object) {
        if (object != null) {
            plateNumber = object.getLicensePlate();
            engineNumber = object.getEngineNumber();
            businessInsuranceExpireDate = object.getBusinessInsuranceExpireDate();
            compulsoryInsuranceExpireDate = object.getCompulsoryInsuranceExpireDate();
            insuranceComp = object.getInsuranceComp();
            if (TextUtils.isEmpty(plateNumber)) {
                plateNumber = parentActivity.getPlateNumber();
            }
            if (TextUtils.isEmpty(engineNumber)) {
                engineNumber = parentActivity.getEngineNumber();
            }
            if (TextUtils.isEmpty(businessInsuranceExpireDate)) {
                businessInsuranceExpireDate = parentActivity.getBusinessInsuranceExpireDate();
            }
            if (TextUtils.isEmpty(compulsoryInsuranceExpireDate)) {
                compulsoryInsuranceExpireDate = parentActivity.getCompulsoryInsuranceExpireDate();
            }
            if (TextUtils.isEmpty(insuranceComp)) {
                insuranceComp = parentActivity.getInsuranceComp();
            }
            parentActivity.setPlateNumber(plateNumber);
            parentActivity.setEngineNumber(engineNumber);
            parentActivity.setBusinessInsuranceExpireDate(businessInsuranceExpireDate);
            parentActivity.setCompulsoryInsuranceExpireDate(compulsoryInsuranceExpireDate);
            parentActivity.setInsuranceComp(insuranceComp);
            showDatas(plateNumber, engineNumber, businessInsuranceExpireDate, compulsoryInsuranceExpireDate, insuranceComp);
        }

    }

    @Override
    public Activity onActivity() {
        return getActivity();
    }

}